"""
Django development settings for luffy project.
"""

from pathlib import Path
import pymysql
import os
import datetime
from datetime import timedelta
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 使用 PyMySQL 替代 MySQLdb
pymysql.install_as_MySQLdb()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent

# 日志文件路径
LOG_PATH = BASE_DIR / "logs"
if not os.path.exists(LOG_PATH):
    os.makedirs(LOG_PATH)

# 日志配置
LOGGING = {
    'version': 1,  # 版本号
    'disable_existing_loggers': False,  # 是否禁用已经存在的日志器
    
    # 日志格式化器
    'formatters': {
        'verbose': {  # 详细格式
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',
        },
        'simple': {  # 简单格式
            'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d][%(message)s]',
        },
    },
    
    # 日志过滤器
    'filters': {
        'require_debug_true': {  # django在debug模式下才输出日志
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    
    # 日志处理器
    'handlers': {
        'console': {  # 输出到控制台
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {  # 输出到文件
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOG_PATH, f'luffy_{datetime.datetime.now().strftime("%Y-%m-%d")}.log'),
            'maxBytes': 300 * 1024 * 1024,  # 300MB
            'backupCount': 10,  # 最多保留10个文件
            'formatter': 'verbose',
            'encoding': 'utf-8'
        },
        'error': {  # 错误日志
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOG_PATH, f'error_{datetime.datetime.now().strftime("%Y-%m-%d")}.log'),
            'maxBytes': 300 * 1024 * 1024,  # 300MB
            'backupCount': 10,  # 最多保留10个文件
            'formatter': 'verbose',
            'encoding': 'utf-8'
        },
    },
    
    # 日志器记录器
    'loggers': {
        'django': {  # django框架相关日志
            'handlers': ['console', 'file', 'error'],
            'propagate': True,
            'level': 'INFO',
        },
        'django.db.backends': {  # 数据库相关日志
            'handlers': ['console', 'file', 'error'],
            'propagate': True,
            'level': 'INFO',
        },
        'apps': {  # 自定义应用日志
            'handlers': ['console', 'file', 'error'],
            'propagate': True,
            'level': 'INFO',
        },
    }
}

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-a9$2i(n-qig880=m+1&tvbk)mt25a23x!s2ou+=zd!v$-#pz(*"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    
    # 第三方应用
    "rest_framework",
    "corsheaders",  # CORS
    
    # 自定义应用
    "home",
    "users",  # 添加users应用
]

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",  # CORS中间件，需要放在最前面
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "luffy.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / 'templates'],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "luffy.wsgi.application"

# 开发环境数据库配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'fuguang',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': 'localhost',
        'PORT': '3306',
        'OPTIONS': {
            'charset': 'utf8mb4',
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
        }
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

LANGUAGE_CODE = "zh-hans"
TIME_ZONE = "Asia/Shanghai"
USE_I18N = True
USE_TZ = True

# 静态文件配置
STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / 'staticfiles'

# 媒体文件配置
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

# Default primary key field type
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# JWT配置
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),  # 访问令牌过期时间
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),  # 刷新令牌过期时间
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,
    'UPDATE_LAST_LOGIN': True,  # 更新最后登录时间
    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'AUTH_HEADER_TYPES': ('Bearer',),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
}

# DRF配置
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

# CORS配置
CORS_ALLOW_CREDENTIALS = True  # 允许携带cookie
CORS_ORIGIN_ALLOW_ALL = False  # 不允许所有域名访问
CORS_ORIGIN_WHITELIST = [
    'http://localhost:5173',  # 允许访问的前端地址
]
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]
CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

# Redis配置
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/0",  # Redis地址
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100},
            "PASSWORD": "",  # Redis密码，如果有的话
        }
    }
}

# 缓存时间配置（单位：秒）
BANNER_CACHE_TIME = 60 * 30  # 轮播图缓存30分钟 

# 自定义用户模型
AUTH_USER_MODEL = 'users.User'

# 阿里云短信服务配置
ALIYUN_SMS = {
    'ACCESS_KEY_ID': os.getenv('ALIYUN_ACCESS_KEY_ID'),  # 从环境变量获取AccessKey ID
    'ACCESS_KEY_SECRET': os.getenv('ALIYUN_ACCESS_KEY_SECRET'),  # 从环境变量获取AccessKey Secret
    'SIGN_NAME': '来嗨',  # 短信签名名称
    'TEMPLATE_CODE': 'SMS_126345035',  # 短信模板CODE
    'ENDPOINT': 'dysmsapi.aliyuncs.com'  # 接入点地址
}

# 短信验证码配置
SMS_CODE = {
    'EXPIRE_TIME': 300,  # 验证码有效期（秒）
    'INTERVAL_TIME': 60,  # 发送间隔时间（秒）
} 